<template>
  <div class="background-container">
    <DynamicBackground/>
    <div class="login-container">
      <div class="login-form">
        <img src="/public/img/logo.png" alt="Logo" class="logo">
        <h2>登录</h2>
        <form v-if="showForm === 1" @submit.prevent="handleLogin">
          <div class="form-group">
            <input type="text" id="username" v-model="username" placeholder="用户名" @focus="clearPlaceholder('username')" required>
          </div>
          <div class="form-group">
            <input type="password" id="password" v-model="password" placeholder="密码" @focus="clearPlaceholder('password')" required>
          </div>
          <div class="button-group">
            <button type="submit">登录</button>
            <button type="button" @click="handleRegister">注册</button>
          </div>
          <a href="/forgotPassword" class="forgot-password-link">忘记密码?</a>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import axios from 'axios';
import { useRouter } from 'vue-router';
import "../css/login.css"
import DynamicBackground from '../components/DynamicBackground.vue';

const showForm = ref(1);

const router = useRouter();

const username = ref('');
const password = ref('');
const ip = "http://localhost:8080/user/login";

const handleLogin = async () => {
  try {
    const userDto = {
      id: NaN,
      username: username.value,
      email: NaN,
      usernameCode: NaN,
      password: password.value,
      birth: NaN,
      captcha: NaN
    };
    const response = await axios.post(ip, userDto, {
      headers: {
        'Content-Type': 'application/json'
      }
    });
    const result = response.data;
    const state = result.state;
    const errMessage = result.errMessage;
    const token =  result.token;
    if(state){
      localStorage.setItem('token',token)
      localStorage.setItem('avatarPath',response.data.data.avatarPath)
      localStorage.setItem('username',response.data.data.username)
      localStorage.setItem('userId',response.data.data.id)
      setTimeout(() => {
        localStorage.removeItem('token');
      }, 86400000); // 24 小时的毫秒数
      router.push({ name: 'Home' });

    }else{
      alert(errMessage)
    }
  } catch (error) {
    console.error('An error occurred:', error);
  }
};

const handleRegister = () => {
  router.push({ name: 'Register' });
};

const clearPlaceholder = (field) => {
  if (field === 'username') {
    username.value = '';
  } else if (field === 'password') {
    password.value = '';
  }
};

</script>


